const {Products,Op}=require('../Model');

let fn_data=async(ctx,next)=>{
    let keyword=ctx.request.query.keyword || '';
    if(keyword){
        ctx.body=await Products.findAll({
            where:{
                [Op.or]:[
                    {id:isNaN(keyword)?-1:keyword},
                    {title:keyword},
                    {abstract:keyword},
                    {content:keyword},
                    {classify:keyword},
                    {author:keyword},
                    {publish:isNaN(keyword)?0:keyword}
                ]
            }
        })
    }else{
        ctx.body=await Products.findAll({
            order:[
                ['id','asc']
            ]
        })
    }
}


//添加
let fn_addOrEndit=async(ctx,next)=>{
    let obj=ctx.request.body;
    let tempobj={};
    tempobj.title=obj.title;
    tempobj.abstract=obj.abstract;
    tempobj.content=obj.content;
    tempobj.classify=obj.classify;
    tempobj.author=obj.author;
    tempobj.publish.obj.publish;

    if(!obj.id){
        let arr=await Products.findAll();
        let temp=arr.filter(item=>{
            return item.title==obj.title
        })
        if(temp.length===0){
            await Products.bulkCreate([
                tempobj
            ]);
            ctx.body={
                code:200,
                data:tempobj,
                msg:'添加成功'
            }
        }else{
            ctx.body={
                code:404,
                data:null,
                msg:'添加失败'
            }
        }
    }else{
        await Products.update({title:obj.title,abstract:obj.abstract,content:obj.content,classify:obj.classify,author:obj.author,publish:obj.publish},{where:{id:obj.id}});
        ctx.body={
            code:1000,
        }
        await Products.findAll();
    }
}

//修改
let fn_endit=async(ctx,next)=>{
    ctx.body=await Products.findAll({
        where:{
            id:parseInt(ctx.request.params.id)
        }
    })
}

//删除
let fn_delete=async(ctx,netx)=>{
    let id=ctx.request.params.id
    await Products.destroy({
        where:{
            id:id
        }
    })
    ctx.body=await Products.findAll({
        order:[
            ['id','asc']
        ]
    })
}


module.exports={
    //展示数据
    'get /produce':fn_data,

    //添加
    'post /produce':fn_addOrEndit,

    //修改
    'get /produce/:id':fn_endit,
    'put /produce':fn_addOrEndit,

    //删除
    'delete /produce/:id':fn_delete
}